<script lang="ts">
  import { Button } from "$lib/components/ui/button";
  import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "$lib/components/ui/card";
  import { Input } from "$lib/components/ui/input";
  import { Label } from "$lib/components/ui/label";
  import { Textarea } from "$lib/components/ui/textarea";
  import { currentReport, isEditing, reportActions, createEmptyReport } from "$lib/store";
  import type { DailyReport } from "$lib/types";
  import { invoke } from '@tauri-apps/api/core';
  import { Copy, Check, Eye, ArrowRight, Calendar } from "lucide-svelte";

  let formData = $state<DailyReport>({
    id: '',
    date: '',
    todayWork: '',
    tomorrowPlan: '',
    createdAt: '',
    updatedAt: ''
  });

  let copied = $state(false);
  let showConvertPrompt = $state(false);
  let canConvert = $state(false);
  
  // 监听当前报告变化
  $effect(() => {
    const current = $currentReport;
    if (current) {
      formData = { ...current };
    } else {
      initializeEmptyReport();
    }
  });

  async function initializeEmptyReport() {
    const emptyReport = await createEmptyReport();
    formData = emptyReport;
  }

  // 初始化
  $effect(() => {
    if (!formData.id) {
      initializeEmptyReport();
    }
  });

  // 检查是否可以转换为周计划
  $effect(async () => {
    if (formData.tomorrowPlan && !formData.weekPlan) {
      const shouldConvert = await invoke<boolean>('should_convert_to_weekly');
      canConvert = shouldConvert;
      showConvertPrompt = shouldConvert;
    } else {
      canConvert = false;
      showConvertPrompt = false;
    }
  });

  async function handleSubmit() {
    if (!formData || !formData.todayWork.trim()) {
      alert('请填写今日工作内容');
      return;
    }

    let success = false;
    
    if ($isEditing && $currentReport) {
      // 更新现有报告
      success = await reportActions.updateReport(formData);
    } else {
      // 创建新报告
      success = await reportActions.addReport(formData);
    }

    if (success) {
      // 重置表单
      await resetForm();
      alert($isEditing ? '日报更新成功！' : '日报保存成功！');
    } else {
      alert('操作失败，请重试');
    }
  }

  async function resetForm() {
    const emptyReport = await createEmptyReport();
    formData = emptyReport;
    reportActions.setCurrentReport(null);
    reportActions.setEditing(false);
  }

  function handleCancel() {
    resetForm();
  }

  // 手动转换为周计划
  async function handleConvertToWeekly() {
    if (!formData.tomorrowPlan) return;
    
    try {
      const weekRange = await invoke<string>('get_week_range');
      formData.weekPlan = `下周计划（${weekRange}）:\n${formData.tomorrowPlan}`;
      formData.tomorrowPlan = '';
      showConvertPrompt = false;
      canConvert = false;
    } catch (error) {
      console.error('转换失败:', error);
      alert('转换失败，请重试');
    }
  }

  async function handleCopyPreview() {
    if (!formData.todayWork.trim()) {
      alert('请先填写今日工作内容');
      return;
    }

    const content = `${formData.date} 工作日报
一、今日工作汇报
${formData.todayWork}

${formData.tomorrowPlan.trim() ? `二、明日工作计划\n${formData.tomorrowPlan}\n` : ''}
${formData.weekPlan ? `三、下周工作计划\n${formData.weekPlan}` : ''}`.trim();

    try {
      await invoke('copy_to_clipboard', { text: content });
      copied = true;
      setTimeout(() => {
        copied = false;
      }, 2000);
    } catch (error) {
      console.error('复制失败:', error);
      alert('复制失败，请重试');
    }
  }



  // 生成预览内容
  function getPreviewContent() {
    if (!formData.todayWork.trim() && !formData.tomorrowPlan.trim()) {
      return '请填写工作内容以查看预览';
    }

    let content = `${formData.date} 工作日报\n\n`;
    
    if (formData.todayWork.trim()) {
      content += `一、今日工作汇报\n${formData.todayWork}\n\n`;
    }
    
    if (formData.tomorrowPlan.trim()) {
      content += `二、明日工作计划\n${formData.tomorrowPlan}\n\n`;
    }
    
    if (formData.weekPlan) {
      content += `三、下周工作计划\n${formData.weekPlan}`;
    }
    
    return content.trim();
  }
</script>

<div class="w-full max-w-6xl mx-auto">
  <!-- 极简标题栏 -->
  <div class="mb-8">
    <div class="flex items-center gap-4">
      <h1 class="text-2xl font-medium text-notion-text">{formData.date} 工作日报</h1>
      <span class="text-sm text-notion-text-secondary">
        {$isEditing ? '编辑模式' : '新建日报'}
      </span>
    </div>
  </div>

  <!-- 主要内容区域 -->
  <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
    <!-- 编辑区域 -->
    <div class="space-y-6">
      <!-- Block 1: 今日工作汇报 -->
      <div class="notion-block">
        <h2 class="text-base font-medium text-notion-text mb-2">一、今日工作汇报</h2>
        <textarea
          id="todayWork"
          placeholder="请输入今天完成的主要工作内容..."
          class="w-full min-h-[140px] p-3 text-sm leading-6 bg-transparent border border-notion-border rounded resize-none focus:outline-none focus:bg-notion-bg-hover transition-colors duration-100"
          bind:value={formData.todayWork}
        ></textarea>
      </div>

      <!-- Block 2: 明日工作计划 -->
      <div class="notion-block">
        <div class="flex items-center justify-between mb-2">
          <h2 class="text-base font-medium text-notion-text">二、明日工作计划</h2>
          {#if canConvert && formData.tomorrowPlan}
            <button
              onclick={handleConvertToWeekly}
              class="px-3 py-1 bg-blue-50 hover:bg-blue-100 text-blue-700 text-xs rounded-full border border-blue-200 transition-colors duration-150 flex items-center gap-1"
            >
              <ArrowRight class="w-3 h-3" />
              转为下周计划
            </button>
          {/if}
        </div>
        <textarea
          id="tomorrowPlan"
          placeholder="请输入明天的工作安排和目标..."
          class="w-full min-h-[120px] p-3 text-sm leading-6 bg-transparent border border-notion-border rounded resize-none focus:outline-none focus:bg-notion-bg-hover transition-colors duration-100"
          bind:value={formData.tomorrowPlan}
        ></textarea>
        
        {#if showConvertPrompt && formData.tomorrowPlan}
          <div class="mt-2 p-3 bg-blue-50 border border-blue-200 rounded text-sm">
            <div class="flex items-start gap-2">
              <Calendar class="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
              <div>
                <p class="text-blue-800 font-medium">周末提醒</p>
                <p class="text-blue-700 text-xs mt-1">
                  今天是周末，建议将明日计划转换为下周工作计划，这样更符合实际工作安排。
                </p>
              </div>
            </div>
          </div>
        {/if}
      </div>

      <!-- Block 3: 下周工作计划 (仅周六显示) -->
      {#if formData.weekPlan}
        <div class="notion-block bg-notion-blue/20 p-4 rounded">
          <h2 class="text-base font-medium text-notion-text mb-2">三、下周工作计划</h2>
          <textarea
            id="weekPlan"
            placeholder="下周的工作安排..."
            class="w-full min-h-[100px] p-3 text-sm leading-6 bg-transparent border border-notion-border rounded resize-none focus:outline-none"
            bind:value={formData.weekPlan}
            readonly
          ></textarea>
          <p class="text-xs text-notion-text-secondary mt-2 italic">💡 周六自动生成的下周计划</p>
        </div>
      {/if}

      <!-- 操作按钮 -->
      <div class="flex gap-2 pt-4">
        <button 
          onclick={handleSubmit} 
          class="px-4 py-2 bg-notion-text text-white text-sm rounded hover:opacity-90 transition-opacity duration-100"
        >
          保存日报
        </button>
        <button 
          onclick={handleCopyPreview}
          class="px-6 py-2.5 bg-green-600 hover:bg-green-700 text-white text-sm rounded font-medium shadow-sm hover:shadow transition-all duration-150 flex items-center gap-2"
        >
          {#if copied}
            <Check class="w-4 h-4" />
            已复制到剪切板
          {:else}
            <Copy class="w-4 h-4" />
            复制日报
          {/if}
        </button>
        <button 
          onclick={handleCancel}
          class="px-4 py-2 text-notion-text-secondary hover:text-notion-text hover:bg-notion-bg-hover text-sm rounded transition-all duration-100"
        >
          清空内容
        </button>
      </div>
    </div>

    <!-- 预览区域 -->
    <div class="bg-notion-bg-secondary/50 rounded p-6">
      <h3 class="text-base font-medium text-notion-text mb-4 flex items-center gap-2">
        <Eye class="w-4 h-4" />
        实时预览
      </h3>
      <div class="bg-white border border-notion-border rounded p-4 min-h-[400px]">
        <pre class="text-notion-text leading-6 whitespace-pre-wrap text-sm font-mono">{getPreviewContent()}</pre>
      </div>

    </div>
  </div>
</div>
